//
//  LrcScrollView.swift
//  QQMusic
//
//  Created by hjj on 2016/12/3.
//  Copyright © 2016年 hjjuny. All rights reserved.
//
import UIKit

private let kLrcCellID = "kLrcCellID"

protocol LrcScrollViewDelegate : class {
    func lrcScrollView(_ lrcScrollView : LrcScrollView, lrcText : String, progress : Double)
    func lrcScrollView(_ lrcScrollView : LrcScrollView, _ nextLrcText : String, _ currentLrcText : String, _ preLrcText : String)
}

class LrcScrollView: UIScrollView {
    
    // MARK: 内部属性
    fileprivate lazy var tableView : UITableView = UITableView()
    fileprivate var lrclines : [LrclineModel]?
    fileprivate var currentLineIndex : Int = 0
    
    // MARK: 对外属性
    weak var lrcDelegate : LrcScrollViewDelegate?
    var currentTime : TimeInterval = 0 {
        didSet {
            // 1.校验歌词数据是否有值
            guard let lrclines = lrclines else {
                return
            }
            
            // 2.遍历所有的歌词
            let count = lrclines.count
            for i in 0..<count {
                // 1.取出当前句的歌词
                let lrcline = lrclines[i]
                
                // 2.取出下一首歌词
                let nextIndex = i + 1
                if nextIndex > count - 1 {
                    continue
                }
                let nextLrcline = lrclines[nextIndex]
                
                // 3.判断当前时间: 大于i位置的歌词,并且小于i+1位置的歌词,则显示i位置的歌词
                if currentTime >= lrcline.lrcTime && currentTime < nextLrcline.lrcTime && i != currentLineIndex {
                    
                    // 1.取出上一个对应的indexPath
                    let preIndexPath = IndexPath(row: currentLineIndex, section: 0)
                    
                    // 2.记录当前i值
                    currentLineIndex = i
                    
                    // 3.取出当前i位置对应的indexPath
                    let indexPath = IndexPath(row: i, section: 0)
                    
                    // 4.刷新两个indexPath
                    tableView.reloadRows(at: [indexPath, preIndexPath], with: .none)
                    
                    // 5.滚动到正确的位置
                    tableView.scrollToRow(at: indexPath, at: .bottom, animated: true)
                    
                    // 6.画出最新歌词的图片
                    drawLrcImage()
                }
                
                // 4.判断是否是在播放同一句歌词
                if i == currentLineIndex {
                    // 4.1.获取当前进度
                    let progress = (currentTime - lrcline.lrcTime) / (nextLrcline.lrcTime - lrcline.lrcTime)
                    
                    // 4.2.取出对应的Cell
                    let indexPath = IndexPath(row: i, section: 0)
                    guard let currentCell = tableView.cellForRow(at: indexPath) as? LrcViewCell else {
                        continue
                    }
                    currentCell.lrcLabel.progress = progress
                    
                    // 4.3.通知代理,并且传入内容
                    lrcDelegate?.lrcScrollView(self, lrcText: lrcline.lrcText, progress: progress)
                }
            }
        }
    }
    var lrcname : String = "" {
        didSet {
            tableView.setContentOffset(CGPoint(x: 0, y: -bounds.height * 0.5), animated: false)
            lrclines = LrcTools.parseLrc(lrcname)
            tableView.reloadData()
            
            currentLineIndex = 0
        }
    }
    
    func setTableViewContentOffset() {
        tableView.setContentOffset(CGPoint(x: 0, y: -bounds.height * 0.5), animated: true)
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        
        setupUI()
    }
}


extension LrcScrollView {
    fileprivate func setupUI() {
        addSubview(tableView)
        
        tableView.backgroundColor = UIColor.clear
        tableView.register(LrcViewCell.self, forCellReuseIdentifier: kLrcCellID)
        tableView.dataSource = self
        tableView.separatorStyle = .none
        tableView.rowHeight = 35
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        let x : CGFloat = bounds.width
        let y : CGFloat = 0
        let w : CGFloat = bounds.width
        let h : CGFloat = bounds.height
        tableView.frame = CGRect(x: x, y: y, width: w, height: h)
        
        tableView.contentInset = UIEdgeInsets(top: bounds.height * 0.5, left: 0, bottom: bounds.height * 0.5, right: 0)
    }
}


// MARK:- UITableView的数据源方法
extension LrcScrollView : UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return lrclines?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: kLrcCellID, for: indexPath) as! LrcViewCell
        
        if indexPath.row == currentLineIndex {
            cell.lrcLabel.font = UIFont.systemFont(ofSize: 16.0)
        } else {
            cell.lrcLabel.font = UIFont.systemFont(ofSize: 14.0)
            cell.lrcLabel.progress = 0
        }
        
        let lrcline = lrclines![indexPath.row]
        cell.lrcLabel.text = lrcline.lrcText
        
        return cell
    }
}



// MARK:- 画出三句歌词
extension LrcScrollView {
    fileprivate func drawLrcImage() {
        // 1.取出三句歌词
        // 1.1.取出本句歌词
        let currentLrcText = lrclines![currentLineIndex].lrcText
        // 1.2.取出上一句歌词
        var previousLrcText = ""
        if currentLineIndex - 1 >= 0 {
            previousLrcText = lrclines![currentLineIndex - 1].lrcText
        }
        // 1.3.取出下一句歌词
        var nextLrcText = ""
        if currentLineIndex + 1 <= lrclines!.count - 1 {
            nextLrcText = lrclines![currentLineIndex + 1].lrcText
        }
        
        // 2.将三句歌词回调给外界控制器
        lrcDelegate?.lrcScrollView(self, nextLrcText, currentLrcText, previousLrcText)
    }
}








